package com.example.industrialpipelinemonitoring.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.industrialpipelinemonitoring.dto.LoginDTO;
import com.example.industrialpipelinemonitoring.dto.UserListDTO;
import com.example.industrialpipelinemonitoring.service.UserService;
import com.example.industrialpipelinemonitoring.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author Dsy
 * @create 2021-11-04  21:59
 */
@RestController
@RequestMapping("user")
public class UserController {


    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public AjaxResult list(@RequestParam String username){
        return userService.listAll();
    }

    @GetMapping("/export")
    public AjaxResult export(@RequestParam String username, HttpServletResponse response){
        List<UserListDTO> rows = userService.listAll2();

        // 通过工具类创建writer，默认创建xls格式id
        ExcelWriter writer = ExcelUtil.getWriter();
        writer.addHeaderAlias("id", "编号");
        writer.addHeaderAlias("userName", "用户名");
        writer.addHeaderAlias("roleName", "角色");
        writer.addHeaderAlias("orgName", "公司名");
        writer.addHeaderAlias("phone", "联系方式");
        writer.addHeaderAlias("createTime", "创建时间");
// 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
//out为OutputStream，需要写出到的目标流

//response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
//test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition","attachment;filename=users.xls");
        ServletOutputStream out= null;
        try {
            out = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        writer.flush(out, true);
// 关闭writer，释放内存
        writer.close();
//此处记得关闭输出Servlet流
        IoUtil.close(out);
        return AjaxResult.success(null);
    }
}
